package asciiTablePrinting;

public final class ASCIITable extends Table {

	public String getTable() {
		validate();
		String tableString = "";
		tableString += getHeadLines();
		tableString += getContentLines();
		return tableString;
	}

	private void validate() {
		validateHeadlines();
		validateEntries();
	}

	private void validateEntries() {
		int entryCount = Integer.MAX_VALUE;
		for (int i = 0; i < columns.size(); i++) {
			if (columns.get(i).getEntryCount() < entryCount) {
				if (entryCount != Integer.MAX_VALUE) {
					throw new IllegalStateException("columns do not have the same number of headlines");
				}
				entryCount = columns.get(i).getEntryCount();
			}
		}
	}

	private void validateHeadlines() {
		int headlineCount = Integer.MAX_VALUE;
		for (int i = 0; i < columns.size(); i++) {
			if (columns.get(i).getHeadlineCount() < headlineCount) {
				if (headlineCount != Integer.MAX_VALUE) {
					throw new IllegalStateException("columns do not have the same number of headlines");
				}
				headlineCount = columns.get(i).getHeadlineCount();
			}
		}
	}

	private String getHeadLines() {
		String headlines = "";

		int headlineCount = getHeadlineCount();

		for (int i = 0; i < headlineCount; i++) {
			for (int j = 0; j < columns.size(); j++) {
				headlines += columns.get(j).getHeadline(i);
			}
			headlines += "\n";
		}
		return headlines;
	}

	private String getContentLines() {
		String contentLines = "";

		int entryCount = getEntryCount();

		for (int i = 0; i < entryCount; i++) {
			for (int j = 0; j < columns.size(); j++) {
				contentLines += columns.get(j).getEntry(i);
			}
			contentLines += "\n";
		}
		return contentLines;
	}

	private int getHeadlineCount() {
		validateHeadlines();
		return columns.get(0).getHeadlineCount();
	}

	private int getEntryCount() {
		validateEntries();
		return columns.get(0).getEntryCount();
	}
}
